package com.yb.guigu.pick.security.provider;

import com.yb.guigu.pick.security.bean.GuiguUsernameCodeAuthenticationToken;
import com.yb.guigu.pick.security.bean.GuiguPickUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/31 14:18
 * FileName: GuiguPickUserPasswordAuthenticationProvider
 * Description:
 */

@Component
@Slf4j
public class GuiguPickUserCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        GuiguUsernameCodeAuthenticationToken authenticationToken= (GuiguUsernameCodeAuthenticationToken) authentication;

        GuiguPickUser guiguPickUser = authenticationToken.getGuiguPickUser();

        String username = guiguPickUser.getUsername();


        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        String code = guiguPickUser.getCode();

        if(!code.equals("123abc")){
            log.debug("Failed to authenticate since password does not match stored value");
            throw new BadCredentialsException("授权码不正确");
        }

        GuiguPickUser successPickUser = new GuiguPickUser();

        BeanUtils.copyProperties(userDetails,successPickUser);

        successPickUser.setLoginType(guiguPickUser.getLoginType());

        successPickUser.setPassword("*************");


        return GuiguUsernameCodeAuthenticationToken.authenticated(guiguPickUser,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return GuiguUsernameCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
